#!/bin/bash
#set -x
#set -e

source ./config/config
source ./script/lib.sh

echo -e "\033[93m|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++|"
echo -e "|     node(通过kubectl和node-exporter调取的接口)                     |"
echo -e "|+++++++++++++++++++++++++++++++++++++++++++++++++++++++++|\033[0m"

echo -e "#################  主机基本信息  #################"
node_basic_info=`kubectl get nodes`

node_basic_info_fatal=`kubectl get nodes | grep NotReady`
if [[ -n $node_basic_info_fatal ]];then
	wResult "FATAL" node_basic_info
else
	wResult "NORMAL" node_basic_info
fi
wDetail "$node_basic_info" node_basic_info

echo -e "#################  主机资源状况  #################"
node_resource_status=`kubectl top nodes`

node_resource_status_fatal=`kubectl top nodes | grep -v NAME | awk '{if($3>90) print $1}' | kubectl top nodes | grep -v NAME | awk '{if($5>90) print $1}'`
node_resource_status_warning=`kubectl top nodes | grep -v NAME | awk '{if($3>80) print $1}' | kubectl top nodes | grep -v NAME | awk '{if($5>80) print $1}'`
if [[ -n $node_resource_status_fatal ]];then
	wResult "FATAL" node_resource_status
elif [[ -n $node_resource_status_warning ]];then
	wResult "WARNING" node_resource_status
else
	wResult "NORMAL" node_resource_status
fi
wDetail "$node_resource_status" node_resource_status

echo -e "#################  硬盘使用情况  #################"
node_exporter_pod_list=`kubectl get pod -n ${NAMESPACE} | grep ${NODE_EXPORTER_NAME} | awk '{print $1}'`

for node_exporter_pod in $node_exporter_pod_list; do
  node_hostname_ipaddress=`kubectl exec -it ${node_exporter_pod} -n ${NAMESPACE} /bin/bash -- hostname -i`
  echo -e "${node_hostname_ipaddress}节点的容器挂载的磁盘如下：" >>$result_dir/node_disk_status_detail

  node_disk_status=`kubectl exec -it ${node_exporter_pod} -n ${NAMESPACE} /bin/bash -- df -h | grep overlay`

  node_disk_status_fatal=`kubectl exec -it ${node_exporter_pod} -n ${NAMESPACE} /bin/bash -- df -h | grep overlay | awk '{if($5>80) print $1}'`
  node_disk_status_warning=`kubectl exec -it ${node_exporter_pod} -n ${NAMESPACE} /bin/bash -- df -h | grep overlay | awk '{if($5>75) print $1}'`
  if [[ -n $node_disk_status_fatal ]];then
  	wResult "FATAL" node_disk_status
  elif [[ -n $node_disk_status_warning ]];then
  	wResult "WARNING" node_disk_status
  else
  	wResult "NORMAL" node_disk_status
  fi
  wDetail "$node_disk_status" node_disk_status
  echo -e "---------------------\n" >>$result_dir/node_disk_status_detail
done
